import { createWebHashHistory } from "vue-router";
import { createRouter } from "vue-router";
import storage from "../utils/storage";

const asyncRoutes = [];
const files = import.meta.glob("@/router/modules/*.js", { eager: true });
for (const f in files) {
  const o = files[f].default;
  asyncRoutes.push(o);
}
console.log(asyncRoutes);

const routes = [
  {
    path: "/",
    component: () => import("@/view/login/index.vue"),
    meta: {
      title: "登录",
    },
  },
  {
    path: "/login",
    component: () => import("@/view/login/index.vue"),
    meta: {
      title: "登录",
    },
  },
  {
    path: "/main",
    component: () => import("@/layout/index.vue"),
    children: asyncRoutes,
  },
];

const router = createRouter({
  routes,
  history: createWebHashHistory(),
});
const whiteRoute = ["/", "/login"];
router.beforeEach((to, from, next) => {
  const token = storage.get("access_token");
  if (whiteRoute.includes(to.path)) {
    next();
    return;
  }
  if (!token && !whiteRoute.includes(to.path)) {
    next("/");
    return;
  }
  next();
  // next({ ...to, replace: true });
});
router.afterEach((to, from, next) => {
  document.title = to.meta.title + " - CarDar 停車系統";
});

export default router;

// export{
//   asyncRoutes
// }
